
/**
 * @description: 遮罩开启 运行中
 * @return {*}
 */
function showLooping() {
  $("#overlay").remove()
  const overlay = $(`<div id="overlay" class="overlay"></div>`);
  const {loopStatus, loopingMsg, loopingStartTime, pluginStartTime, pluginEndTime} = globalData
  const {channel, shop_name} = pluginInfo
  const bottom_tips = loopStatus ? `开始运行于${pluginStartTime}` : `异常停止时间：${pluginEndTime}`
  const logoPath = tabTypes.find(item => item.channel === Number(channel)).logoPath
  const iconUrl = chrome.runtime.getURL(`../asset/img/${logoPath}.png`);
  const {total_order_full, total_goods_full, total_order_increment, total_goods_increment, today_order_full, today_goods_full, today_order_increment, today_goods_increment} = statisticsData
  const {recently_sync_date_order, recently_sync_date_goods} = recentlySyncDate
  const innerContentHtml = 
      `
        <div class="content">
          <div class="layout title">零售订单小助手</div>
          <div class="data_box store_info">
            <div class="store_logo">
              <img id="store_logo" src="${iconUrl}" alt="">
            </div>
            <div id="store_name" class="store_name">${shop_name}</div>
            <div id="store_status" class="store_status ${!loopStatus ? 'store_status_err' : ''}">${loopingMsg}</div>
          </div>
          <div class="data_title">数据概览<span class="statistical_time" id="statistical_time">数据统计时间：${loopingStartTime} 至今</span></div>
          <div class="data_box overview">
            <div id="orders" class="overview_item">
              <div class="overview_item_title">订单数</div>
              <div id="total_order_full" class="overview_item_total">${total_order_full}</div>
              <div class="overview_item_today">今日：<span id="today_order_full" class="num_today">${today_order_full}</span></div>
            </div>
            <div id="goods" class="overview_item">
              <div class="overview_item_title">商品数</div>
              <div id="total_goods_full" class="overview_item_total">${total_goods_full}</div>
              <div class="overview_item_today">今日：<span id="today_goods_full" class="num_today">${today_goods_full}</span></div>
            </div>
            <div id="ordersMsg" class="overview_item">
              <div class="overview_item_title">订单消息处理</div>
              <div id="total_order_increment" class="overview_item_total">${total_order_increment}</div>
              <div class="overview_item_today">今日：<span id="today_order_increment" class="num_today">${today_order_increment}</span></div>
            </div>
            <div id="goodsMsg" class="overview_item">
              <div class="overview_item_title">商品消息处理</div>
              <div id="total_goods_increment" class="overview_item_total">${total_goods_increment}</div>
              <div class="overview_item_today">今日：<span id="today_goods_increment" class="num_today">${today_goods_increment}</span></div>
            </div>
          </div>
          <div class="data_title">功能操作</div>
          <div class="data_box handle">
            <div class="handle_title">
              <span class="handle_title_text">订单服务：</span>
              <button id="sync_orders_btn" class="handle_title_btn" onclick="syncHisOrders()">同步历史订单</button>
            </div>
            <div class="handle_box">
              <div class="handle_box_item">
                <span class="handle_box_item_label">订单信息：</span>
                <span class="handle_box_item_content">最近同步时间：<span id="recently_sync_date_order">${recently_sync_date_order || '--'}</span></span>
              </div>
            </div>
          </div>
          <div class="data_box handle">
            <div class="handle_title">
              <span class="handle_title_text">商品服务：</span>
              <button id="sync_goods_btn" class="handle_title_btn" onclick="syncHisGoods()">同步历史商品</button>
            </div>
            <div class="handle_box">
              <div class="handle_box_item">
                <span class="handle_box_item_label">商品信息：</span>
                <span class="handle_box_item_content">最近同步时间：<span id="recently_sync_date_goods">${recently_sync_date_goods || '--'}</span></span>
              </div>
            </div>
          </div>
          <div class="layout bottom">
            <div id="tips" class="tips ${!loopStatus ? 'err': ''}">${bottom_tips}</div>
            <div id="stopLoop" class="button" onclick="finishScript()">${loopStatus ? '停止' : '重新配置'}</div>
          </div>
        </div>
      `;
  overlay.html(innerContentHtml);
  $("body").append(overlay);
}


/**
 * @description: 更新同步数据次数（视图）
 * @return {*}
 */    
function updateSyncTimesViews(){
  const {total_order_full, total_goods_full, total_order_increment, total_goods_increment, today_order_full, today_goods_full, today_order_increment, today_goods_increment} = statisticsData
  $("#total_order_full").text(total_order_full);
  $("#total_goods_full").text(total_goods_full);
  $("#total_order_increment").text(total_order_increment);
  $("#total_goods_increment").text(total_goods_increment);
  $("#today_order_full").text(today_order_full);
  $("#today_goods_full").text(today_goods_full);
  $("#today_order_increment").text(today_order_increment);
  $("#today_goods_increment").text(today_goods_increment);
}


/**
* @description: 更新最近同步数据日期时间（视图）
* @return {*}
*/
function updateSyncDateViews(){
  const {recently_sync_date_order, recently_sync_date_goods} = recentlySyncDate
  $("#recently_sync_date_order").text(recently_sync_date_order);
  $("#recently_sync_date_goods").text(recently_sync_date_goods);
}


/**
* @description: 更新插件运行状态（视图）
* @return {*}
*/
function updateLoopStatusViews(){
  const {loopStatus, loopingMsg, pluginStartTime, pluginEndTime} = globalData
  $("#store_status").text(loopingMsg);
  if($("#store_status").hasClass('store_status_err')){
      $("#store_status").removeClass('store_status_err')
  }
  if($("#tips").hasClass('err')){
      $("#tips").removeClass('err')
  }
  if(loopStatus){
    $("#tips").text(`开始运行于${pluginStartTime}`);
    $("#stopLoop").text('停止')
    confirms.index = 0
  }else{
    $("#store_status").addClass('store_status_err')
    $("#tips").addClass('err')
    $("#tips").text(`异常停止时间：${pluginEndTime}`);
    $("#stopLoop").text('重新配置')
    confirms.index = 1
  }
}



/**
 * @description: 停止运行确认
 * @return {*}
 */
function stopConfirmFn(){
  const overlay_confirm = $(`<div id="overlay_confirm" class="overlay_confirm"></div>`);
  const {index, list} = confirms
  const innerConfirmHtml = 
    `
      <div class="confirm">
        <div class="layout title">提示</div>
        <div id="confirm_content" class="confirm_content">${list[index]}</div>
        <div class="layout bottom">
          <div class="button cancal" onclick="closeConfirmScript()">取消</div>
          <div class="button sure" onclick="stopLoopFnScript()">确定</div>
        </div>
      </div>
    `;
  overlay_confirm.html(innerConfirmHtml);
  $("body").append(overlay_confirm);
}


/**
 * @description: 清空本地缓存的统计数据信息
 * @return {*}
 */
async function clearLocalStorageData(){
  const loopingStartTime = getDateLocaleString()
  await chrome.storage.local.set({loopingStartTime})
  globalData.loopingStartTime = loopingStartTime
  const local_data_st = { 'total_order_full': 0, 'total_goods_full': 0, 'total_order_increment': 0, 'total_goods_increment': 0, 'today_order_full': 0, 'today_goods_full': 0, 'today_order_increment': 0, 'today_goods_increment': 0 }
  await chrome.storage.local.set(local_data_st)
  statisticsData.total_order_full = 0
  statisticsData.total_goods_full = 0
  statisticsData.total_order_increment = 0
  statisticsData.total_goods_increment = 0
  statisticsData.today_order_full = 0
  statisticsData.today_goods_full = 0
  statisticsData.today_order_increment = 0
  statisticsData.today_goods_increment = 0
  const local_data_re = {"recently_sync_date_order": '', "recently_sync_date_goods": ''}
  await chrome.storage.local.set(local_data_re)
  recentlySyncDate.recently_sync_date_order = ''
  recentlySyncDate.recently_sync_date_goods = ''
}


/**
 * @description: 提示框
 * @param {*} state 消息类型 message success warning error
 * @param {*} msg 消息内容
 * @param {*} delay 显示时间 默认5秒
 * @return {*}
 */
function toastMessage(state = 'message', msg = '', delay = 5000) {
  let toastQueue = $("#toastQueue")
  if(!toastQueue.length){
    toastQueue = $(`<div id="toastQueue" class="toastQueue"></div>`)
    $("body").append(toastQueue);
  }
  const dom_id = Math.random().toString(36).slice(-6) || Math.random().toString(36).slice(-6)
  const innerToastHtml = $(`<div id="innerToastHtml_${dom_id}" class="innerToastHtml ${state}">${msg}</div>`);
  toastQueue.append(innerToastHtml);
  setTimeout(() => {
    $(`#innerToastHtml_${dom_id}`).remove();
  }, delay);
}


/**
 * @description: 计算接口请求频次
 * @param {*} current_timestamp  时间戳
 * @return {*}
 */
function calcRequestTimes(current_timestamp){
  if(globalData.request_timestamp){
    if(current_timestamp - globalData.request_timestamp > 1000 * RANGE){
      globalData.request_timestamp = current_timestamp
      globalData.request_times = 1
      globalData.is_request_exceed = false
      globalData.request_timestamp_gap = 0
    }else if(globalData.request_times > FRENQUENCY){
      globalData.request_timestamp_gap = current_timestamp - globalData.request_timestamp
      globalData.is_request_exceed = true
      globalData.request_timestamp = current_timestamp
      globalData.request_times = 0
    }else{
      globalData.is_request_exceed = false
      globalData.request_times++
      globalData.request_timestamp_gap = 0
    }
  }else{
    globalData.is_request_exceed = false
    globalData.request_timestamp = current_timestamp
    globalData.request_times++
    globalData.request_timestamp_gap = 0
  }
}


/**
 * @description: 检查频次
 * @cb  回调
 * @return {*}
 */
function inspectFrequency(cb){
  return new Promise(resolve => {
    if(globalData.is_request_exceed){
      setTimeout(() => {
        cb && cb()
        resolve()
      }, globalData.request_timestamp_gap)
    }else{
      cb && cb()
      resolve()
    }
  })
}


/**
 * @description: 往后台脚本发送消息
 * @param {*} type   send数据（string/object）
 * @cb   回调
 * @return {*}
 */
function sendRunTimeMessage(type, cb){
  const {currentTabId: tabId} = globalData
  const data = typeof type === 'string' ? {type, tabId} : type
  return chrome.runtime.sendMessage(data, res => {
    cb && cb(res)
  })
}


/**
 * @description: 设置同步按钮状态
 * @param {*} type 1 订单   2 商品
 * @param {*} status 1 可同步   2 同步中   3 同步完成
 * @return {*}
 */
function setBtnStatus(type = 1, status = 1){
  let btnDom = ''
  let btnText = ''
  let btnDisabled = false
  btnDom = type === 1 ? "#sync_orders_btn" : "#sync_goods_btn"
  btnText = status === 2 ? '同步中' : `同步历史${type === 1 ? "订单" : "商品"}`
  btnDisabled = status === 2 ? true : false
  $(btnDom).text(btnText)
  $(btnDom).attr("disabled", btnDisabled)
}


/**
 * @description: 根据id计算同步数据长度
 * @param {*} type  1 订单   2 商品
 * @param {*} idList  需要同步的数据id数组
 * @return {*}
 */
function getSyncLength(type, idList){
  const localText = type === 1 ? 'sync_order_id_list' : 'sync_goods_id_list'
  const num = type === 1 ? MAX_SYNC_NUM_ORDER : MAX_SYNC_NUM_GOODS
  const bloomsType = type === 1 ? 'orderBlooms' : 'goodsBlooms'
  return new Promise((resolve) => {
    chrome.storage.local.get(localText, res => {
      let bitArray = []
      if(res[localText]){
        bitArray = res[localText]
      }else{
        bitArray = new Array(num).fill(false)
      }
      if(!blooms[bloomsType].hashFunctions.length){
        blooms[bloomsType].hashFunctions = [(element) => hashFunction(element, num)];
      }
      if(!blooms[bloomsType].bloomFilter){
        blooms[bloomsType].bloomFilter = new BloomFilter(num, blooms[bloomsType].hashFunctions, bitArray);
      }
      const statistics = idList.reduce((pre, cur) => {
        if(!blooms[bloomsType].bloomFilter.contains(cur)){
          blooms[bloomsType].bloomFilter.insert(cur)
          pre++
        }
        return pre
      }, 0)
      const local_data = {[localText]: blooms[bloomsType].bloomFilter.bitArray}
      chrome.storage.local.set(local_data, () => resolve(statistics))
    })
  })
}


/**
 * @description: 获取当前时间
 * @param {*} date  时间戳
 * @return {*}
 */
function getDateLocaleString(data = Date.now()){
  return new Date(data).toLocaleString('zh-cn',{year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false}).replaceAll('/', '-')
}


/**
 * @description: 获取当前插件运行url
 * @return {*}
 */
function getCurrentTabUrl(){
  let permssions_url = ''
  Object.keys(PERMSSIONS_ENVS).some(key => {
    return tabTypes.some(item => {
      const url_name = `PERMSSIONS_URL_${item.logoPath}`
      if(location.href.includes(PERMSSIONS_ENVS[key][url_name])){
        globalData.channel = item.channel
        env_type = key
        permssions_url = PERMSSIONS_ENVS[key][url_name]
        initTabTypeUrl(key)
        return true
      }else{
        return false
      }
    })
  })
  return permssions_url
}


/**
 * @description: 初始化店铺数据
 * @param {*} env_  环境 dev test pro
 * @return {*}
 */
function initTabTypeUrl(env_){
  tabTypes.forEach(item => {
    const url_name = `PERMSSIONS_URL_${item.logoPath}`
    const base_url_name = `PERMSSIONS_BASE_URL_${item.logoPath}`
    item.url = PERMSSIONS_ENVS[env_][url_name]
    item.baseURL = PERMSSIONS_ENVS[env_][base_url_name]
  })
}